package cn.lexi.vip.controller;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author Aaron
 */
public interface IBaseController {

    String SUCCESS = "success";

    String FAILED = "failed";

    String OK = "ok";
     static final Logger LOGGER = LoggerFactory.getLogger(IBaseController.class);



    default HttpSession getSession() {
        return getRequest().getSession();
    }


    default HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return attrs.getRequest();
    }

    default String getIp() {
        HttpServletRequest request = getRequest();

        String ip = request.getParameter("ip");
        if (StringUtils.isNotEmpty(ip)) {
            return ip;
        }
        ip = request.getHeader("x-real-ip");
        if (StringUtils.isEmpty(ip)) {
            ip = request.getRemoteAddr();
        }

        //过滤反向代理的ip
        String[] stemps = ip.split(",");
        if (stemps.length >= 1) {
            //得到第一个IP，即客户端真实IP
            ip = stemps[0];
        }

        ip = ip.trim();
        if (ip.length() > 23) {
            ip = ip.substring(0, 23);
        }
        return ip;
    }
}
